package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.dto.RoleDTO;
import com.example.entity.RoleDO;
import com.example.exception.BusinessException;
import com.example.mapper.RoleMapper;
import com.example.service.RoleService;
import java.util.Date;
import java.util.List;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   角色管理服务层实现
 * </p>
 * @author 34448
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public Boolean addRole(RoleDTO roleDTO) {
        QueryWrapper<RoleDO> wrapper = Wrappers.query();
        wrapper.eq("role_name", roleDTO.getRoleName());
        RoleDO existingRole = roleMapper.selectOne(wrapper);
        if (existingRole != null) {
            throw new BusinessException("000001", "角色名称已存在");
        }
        RoleDO roleDO = new RoleDO();
        BeanUtils.copyProperties(roleDTO, roleDO);
        roleDO.setCreateTime(new Date());
        roleDO.setUpdateTime(new Date());
        return roleMapper.insert(roleDO) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteRole(Integer roleId) {
        RoleDO roleDO = roleMapper.selectById(roleId);
        if (roleDO == null) {
            throw new BusinessException("000001", "角色信息不存在");
        }
        return roleMapper.deleteById(roleId) > 0;
    }

    @Override
    @Transactional
    public Boolean editRole(RoleDTO roleDTO) {
        RoleDO roleDO = roleMapper.selectById(roleDTO.getRoleId());
        if (roleDO == null) {
            throw new BusinessException("000001", "角色信息不存在");
        }
        QueryWrapper<RoleDO> wrapper = Wrappers.query();
        wrapper.eq("role_name", roleDTO.getRoleName()).ne("role_id", roleDTO.getRoleId());
        RoleDO existingRole = roleMapper.selectOne(wrapper);
        if (existingRole != null) {
            throw new BusinessException("000001", "角色名称已存在");
        }
        BeanUtils.copyProperties(roleDTO, roleDO);
        roleDO.setUpdateTime(new Date());
        return roleMapper.updateById(roleDO) > 0;
    }

    @Override
    public List<RoleDO> queryRoles(String roleName) {
        QueryWrapper<RoleDO> wrapper = Wrappers.query();
        if (roleName != null && !roleName.isEmpty()) {
            wrapper.like("role_name", roleName);
        }
        return roleMapper.selectList(wrapper);
    }
}